package com.sgb.capital.viewmodel;

import android.app.Application;
import android.view.View;
import android.widget.CheckBox;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableField;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.sgb.capital.api.CapitalManager;
import com.sgb.capital.model.BaseEntity;
import com.sgb.capital.model.InvoiceFeesBean;
import com.sgb.capital.utils.DialogHelper;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.ui.activity.ConfirmInvoiceAndAddressActivity;
import com.sgb.capital.view.ui.adapter.InvoiceFlowAdapter;
import com.sgb.capital.view.widget.MToast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import razerdp.basepopup.BasePopupSDK;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 开票列表
 * @author cyj
 */
public class InvoiceFlowModel extends AndroidViewModel {

    /** 是否选择了所有的流水数据，没有新刷新数据时，默认选择一页数据x<=20条 */
    public ObservableBoolean hasCheckedAll = new ObservableBoolean(false);
    /** 开票流水适配器 */
    public InvoiceFlowAdapter invoiceFlowAdapter;
    /** 开票流水列表数据 */
    public List<InvoiceFeesBean> invoiceFlowList = new ArrayList<>();
    public MutableLiveData<List<InvoiceFeesBean>> invoiceFlowListLiveData = new MutableLiveData<>();
    /** 全选金额总计 */
    public ObservableField<String> totalMoney = new ObservableField("0.00");
    /** 全选数量总计 */
    public ObservableField<Integer> selectTotal = new ObservableField(0);

    public ObservableField<InvoiceFeesBean> invoiceFeesBean = new ObservableField<>(new InvoiceFeesBean());

    public InvoiceFlowModel(@NonNull Application application) {
        super(application);
        invoiceFlowAdapter = new InvoiceFlowAdapter(application.getApplicationContext(), null);
    }

    /** 网络获取开票流水列表数据 */
    public void getInvoiceFlowList(InvoiceFeesBean invoiceFeesBean) {
        clear(invoiceFeesBean.page);
        DialogHelper.showProgressDialog(BasePopupSDK.getInstance().getTopActivity(),"数据加载中").setCanceledOnTouchOutside(false);
        CapitalManager.getInstance().getCapitalAPI().invoiceFeesList(invoiceFeesBean).enqueue(new Callback<BaseEntity<InvoiceFeesBean>>() {

            @Override
            public void onResponse(Call<BaseEntity<InvoiceFeesBean>> call, Response<BaseEntity<InvoiceFeesBean>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(CapitalManager.RESPONSE_OK)) {
                    invoiceFlowList.addAll(response.body().getData().list);
                    invoiceFlowListLiveData.setValue(invoiceFlowList);
                    invoiceFlowAdapter.setDatas(invoiceFlowList);
                    invoiceFlowAdapter.notifyDataSetChanged();
                    hasCheckedAll.set(response.body().getData().list.size() <= 0);
                } else {
                    MToast.showToast(getApplication(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<InvoiceFeesBean>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(getApplication(), t.getMessage());
            }
        });
    }

    /** 全选按钮被选中时，全选共计金额计算并更新UI */
    public void cbxClickForAddMoney(View checkBox) {
        boolean isChecked = ((CheckBox) checkBox).isChecked();
        BigDecimal money = new BigDecimal("0.00");
        if(isChecked && invoiceFlowList.size() > 0) {
            for (InvoiceFeesBean bean: invoiceFlowList) {
                money = money.add(new BigDecimal(bean.tradeFees));
                bean.isChecked.set(true);
            }
            totalMoney.set(money.toString());
            selectTotal.set(invoiceFlowList.size());
        } else {
            for (InvoiceFeesBean bean: invoiceFlowList) {
                bean.isChecked.set(false);
            }
            totalMoney.set("0.00");
            selectTotal.set(0);
        }
    }

    /** 列表item选中时，金额计算并更新UI */
    public void itemClickForAddMoney(InvoiceFeesBean bean) {
        BigDecimal totalMoneyBigDecimal = new BigDecimal(totalMoney.get());
        if(bean.isChecked.get()) {
            // item选中则增加金额
            totalMoney.set(totalMoneyBigDecimal.add(new BigDecimal(bean.tradeFees)).toString());
            selectTotal.set(selectTotal.get() + 1);
        } else if(totalMoneyBigDecimal.compareTo(new BigDecimal("0")) > 0 && !bean.isChecked.get()) {
            // item选中则减去金额，此处默认数值大于0则执行减去算法
            totalMoney.set(totalMoneyBigDecimal.subtract(new BigDecimal(bean.tradeFees)).toString());
            selectTotal.set(selectTotal.get() - 1);
        }
    }

    private void clear(int page) {
        if(page == 1 && null != invoiceFlowList && invoiceFlowList.size() > 0) {
            invoiceFlowList.clear();
            invoiceFlowAdapter.notifyDataSetChanged();
            selectTotal.set(0);
            totalMoney.set("0.00");
        }
    }

    /** 获取选中的数据列表 */
    private String[] getIds() {
        List<String> ids = new ArrayList<>();
        for (InvoiceFeesBean bean: invoiceFlowList) {
            if(bean.isChecked.get()) {
                ids.add(bean.id);
            }
        }
        return ids.toArray(new String[0]);
    }

    /**
     * (button点击事件)索取发票
     * 流程：判断用户是否有选中发票，默认未选中情况下发票金额为0，则弹窗引导；反之，跳转确认发票页面
     */
    public void btnClickForGetInvoice() {
        if(new BigDecimal(totalMoney.get()).compareTo(new BigDecimal("0.00")) <= 0) {
            new TipPop(getApplication(),
                    "温馨提示",
                    "请勾选需要开具发票的流水。",
                    null,
                    "知道了").show();
            return;
        }

        // 确认发票跳转 ConfirmInvoiceAndAddressActivity
        ConfirmInvoiceAndAddressActivity.start(BasePopupSDK.getInstance().getTopActivity(), totalMoney.get(), getIds());
    }

}